#include ".\gametable.h"
#include "Player.h"
#include "GameRoom.h"

IGameTable::IGameTable(IGameRoom *room)
{
    _DEBUG_CHECK(room);
    m_pRoom = room;
    m_State = eTABLE_NORMAL;
    m_Index = -1;
    _Init(room->getGameInfo()->getPlayerCount());
}

IGameTable::~IGameTable(void)
{
    Clear();
}

void IGameTable::_Init(int nPlayerCount)
{
    Clear();
    m_arrPlayers.resize(nPlayerCount);
    for(int i = 0;i < m_arrPlayers.size();i++)
        m_arrPlayers[i] = NULL;
}

void IGameTable::Clear()
{
    m_arrPlayers.clear();
    m_arrWatcher.clear();
}

bool IGameTable::PlayerSit(BYTE seat,IPlayer *player)
{
    if(seat >= m_arrPlayers.size())
        return false;

    assert( player );

    m_arrPlayers[seat] = player;
    player->setSeat(seat);
    player->setSeeWho(NULL);
    player->setTable(this);
    return true;
}

bool IGameTable::PlayerSee(BYTE seat,IPlayer *player)
{
    if(seat >= m_arrPlayers.size())
        return false;

    assert( GetPlayer(seat) );

    player->setSeat(seat);
    player->setSeeWho( GetPlayer(seat) );

    for (size_t i = 0;i < m_arrWatcher.size();i++)
    {
        if(m_arrWatcher[i] == player) return true;
    }

    m_arrWatcher.push_back(player);

    return true;
}

bool IGameTable::PlayerOut(IPlayer *player)
{
    assert( player );
    if( player->getTable() != this )
        return false;
    if( player->getSeeWho() == NULL )
    {
        m_arrPlayers[player->getSeat()] = NULL;
    }
    else
    {
        player->setSeeWho(NULL);
        for (size_t i = 0;i < m_arrWatcher.size();i++)
        {
            if(m_arrWatcher[i] == player)
            {
                m_arrWatcher.erase(m_arrWatcher.begin() + i);
            };
        }
    }
    player->setTable(NULL);
    return true;
}

SEAT_ID IGameTable::GetPlayerSeat(IPlayer *player)const
{
    assert( player );
    if(player->getSeeWho() != NULL)
    {
        for (size_t i = 0;i < m_arrWatcher.size();i++)
        {
            if(m_arrWatcher[i] == player)
            {
                return i;
            };
        }
    }
    else
    {
        for (size_t i = 0;i < m_arrPlayers.size();i++)
        {
            if(m_arrPlayers[i] == player)
            {
                return i;
            };
        }
    }

    return SEAT_ID(-1);
}

IPlayer *IGameTable::getSelf()
{
    return m_pRoom->getSelf();
}

bool IGameTable::SendPacket(const void *data,size_t size)
{
    _DEBUG_CHECK(m_pRoom);
    return m_pRoom->SendPacket(data,size);
}

void IGameTable::IWantLeave()
{
    _DEBUG_CHECK(m_pRoom);
    m_pRoom->QuestLeaveTable();
}

MONEY_ID IGameTable::getGameMoney(IPlayer *player)
{
    CGameInfo *info = m_pRoom->getGameInfo();
    if (IS_MONEY_GAME(info))
        return player->getMoney();
    else if (IS_SCORE_GAME(info))
        return player->getScore();
    else
        return 0;
}